<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\App;
use think\Cache;
use think\Config;
use think\Db;
use think\Exception;
use think\Log;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'userlogin'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="account", type="string", required=true, description="账号")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="code", type="string", required=true, description="验证码")
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @ApiParams (name="avatar", type="string", required=true, description="头像地址")
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams (name="bio", type="string", required=true, description="个人简介")
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="platform", type="string", required=true, description="平台名称")
     * @ApiParams (name="code", type="string", required=true, description="Code码")
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="newpassword", type="string", required=true, description="新密码")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
    /*
     * 用户登录
     *
     *
     */
    public function userlogin()
    {
        $param = $this->request->param();
        $xcxConfig = db('xcx_config')->find(1);
        $appid = $xcxConfig['appid'];
        $secret = $xcxConfig['secret'];
        // 获取前端传来的 code
        $code = $param['code'];
        // 调用微信 API 换取 openid 和 session_key
        $apiUrl = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        $response = file_get_contents($apiUrl);
        $data = json_decode($response, true);
        //用户登录
        $user = '';
        if (isset($data['openid'])) {
            $user = Db::table('car_user')->where('openid', $data['openid'])->find();
        }

        if (!empty($user)) {
            $ret = $this->auth->direct($user['id']);
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            $this->success('登录成功', ['userinfo' => $this->auth->getUserinfo()]);
        } else {
            $username = Random::alnum(10);
            $password = "123456";
            $email = $username . "@admin.com";
            $mobile = '';
            $openid = $data['openid'];
            $ret = $this->auth->registeruser($username, $password, $email, $mobile, [], $openid);
            if ($ret) {
                $this->success('登录成功', ['userinfo' => $this->auth->getUserinfo()]);
            } else {
                $this->error($this->auth->getError());
            }
        }
    }
    //获取access_token
    public function getAccessToken()
    {

        $xcxConfig = db('xcx_config')->find(1);
        $appid = $xcxConfig['appid']; // 替换为你的小程序 appid
        $secret = $xcxConfig['secret']; // 替换为你的小程序 secret
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $res = curl_exec($curl);
        curl_close($curl);
        return json_decode($res)->access_token;
    }
    /**
     * 获取用户手机号
     */
    public function getPhoneNumber()
    {
        $param = $this->request->param();
        $code = $param['code']; // 获取前端传递的code
        $accessToken = $this->getAccessToken(); // 获取access_token
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$accessToken";
        $data = ['code' => $code];
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $res = curl_exec($curl);
        curl_close($curl);
        $resData = json_decode($res, true);
        $user_id = $this->auth->id;
        if (empty($user_id)) {
            $this->error('登录失败');
        }
        if ($resData['errcode'] == 0) {
            Db::table('car_user')->where('id', $user_id)->update(['mobile' => $resData['phone_info']['phoneNumber']]);
            $this->success('登录成功');
        } else {
            $this->error('请求失败');
        }
    }
    /**
     * 查看个人信息
     */
    public function userinfo()
    {
        $user = $this->auth->getUserinfo();
        switch ($user['stutes']) {
            case 0:
                $user['stutes_text'] = '未认证';
                break;
            case 1:
                $user['stutes_text'] = '认证中';
                break;
            case 2:
                $user['stutes_text'] = '已认证';
                break;
            case 3:
                $user['stutes_text'] = '认证失败';
                break;
            default:
                $user['stutes_text'] = '未知状态';
                break;
        }
        $user['avatar'] = cdnurl($user['avatar'], true);
        $user['wx_image'] = cdnurl($user['wx_image'], true);
        $this->success('个人信息', ['userinfo' => $user]);
    }
    /**
     * 用户认证
     */
    public function submitUserAuth()
    {
        $param = $this->request->param();
        $user_id = $this->auth->id;
        // $user_id = 1;
        $stutes = Db::name('user')->where('id', $user_id)->value('stutes');
        if ($stutes == 1) {
            $this->error('请勿重复提交');
        }
        if (empty($param['username']) || empty($param['mobile']) || empty($param['idcard']) || empty($param['idfront_image']) || empty($param['idback_image']) || empty($param['province_city']) || empty($param['urban_city']) || empty($param['district_city'])) {
            $this->error('请填写完整信息');
        }
        // 验证短信验证码
        $mobile = $param['mobile'];
        $code = $param['code'];
        if (empty($code)) {
            $this->error('验证码不能为空');
        }
        $res = $this->checkSmsCode($mobile, $code);
        if (!$res['code']) {
            $this->error($res['msg']);
        }
        $options = [
            'username' => $param['username'],
            'mobile_r' => $param['mobile'],
            // 'mobile' => $param['mobile'],
            'idcard' => $param['idcard'],
            'idfront_image' => $param['idfront_image'],
            'idback_image' => $param['idback_image'],
            'province_city' => $param['province_city'],
            'urban_city' => $param['urban_city'],
            'district_city' => $param['district_city'],
            // 'wx_image' => $param['wx_image'],
            'authen_time' => time(),
            'stutes' => '1',
        ];
        Db::startTrans();
        try {
            $res = Db::name('user')->where('id', $user_id)->update($options);
            if ($res) {
                Db::commit();
                $this->success('提交成功,请耐心等待审核!');
            } else {
                throw new Exception('提交失败');
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error('提交失败');
        }
    }
    /**
     * 认证查询
     */
    public function userAuthQuery()
    {
        $user_id = $this->auth->id;
        // $user_id = 1;
        $stutes = Db::name('user')->where('id', $user_id)->value('stutes');
        $userInfo = Db::name('user')->where('id', $user_id)->field('id,username,mobile_r,idcard,idfront_image,idback_image,wx_image,province_city,urban_city,district_city,reason,authen_time,shen_time')->find();
        $userInfo['province_city_name'] = get_city_name($userInfo['province_city']);
        $userInfo['urban_city_name'] = get_city_name($userInfo['urban_city']);
        $userInfo['district_city_name'] = get_city_name($userInfo['district_city']);
        $userInfo['address_all'] = $userInfo['province_city_name'] . $userInfo['urban_city_name'] . $userInfo['district_city_name'];
        $userInfo['wx_image'] = cdnurl($userInfo['wx_image'], true);
        switch ($stutes) {
            case 0:
                $this->success('未认证', ['stutes' => 0, 'userInfo' => $userInfo]);
                break;
            case 1:
                $this->success('认证中', ['stutes' => 1, 'userInfo' => $userInfo]);
                break;
            case 2:
                $this->success('已认证', ['stutes' => 2, 'userInfo' => $userInfo]);
                break;
            case 3:
                $this->success('认证失败', ['stutes' => 3, 'userInfo' => $userInfo]);
                break;
            default:
                $this->error('未知状态');
                break;
        }
    }
    /**
     * 修改个人信息
     */
    public function editUserInfo()
    {
        $user = $this->auth->getUser();
        //$username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        $wx_image = $this->request->post('wx_image', '', 'trim,strip_tags,htmlspecialchars');
        $avatar = parse_url($avatar)['path'];
        $wx_image = parse_url($wx_image)['path'];
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->avatar = $avatar;
        $user->wx_image = $wx_image;
        $user->save();
        $this->success();
    }
    //发送短信(app登录时使用)
    public function loginSendMsg()
    {
        $mobile = $this->request->post('phone');

        if (empty($mobile)) {
            $this->error('请输入手机号');
        }

        if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
            $this->error('请填写正确的手机号');
        }

        // 频率限制检查
        $lastSendTime = Cache::get('sms_limit_' . $mobile);
        if ($lastSendTime && time() - $lastSendTime < 60) {
            $this->error('请求过于频繁，请稍后再试');
        }

        $mobile_code = rand(100000, 999999);

        $account = 'chaijian';
        $content = '【拆件砖家】您的手机验证码是:' . $mobile_code;

        // 生成时间参数
        $tKey = time(); // 10位时间戳
        $md5pass = md5('Chaijian2025');
        $password = md5($md5pass . $tKey); // 二次加密

        // 构建请求数据
        $postData = [
            'username' => $account,
            'password' => $password,
            'tKey' => $tKey,
            'mobile' => $mobile,
            'content' => $content,
            // 'time' => '', // 定时发送，留空立即发送
            // 'ext' => '', // 扩展号
            // 'extend' => '' // 自定义参数
        ];

        $url = 'https://api-shss.zthysms.com/v2/sendSms';

        // 使用cURL发送POST请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Content-Length: ' . strlen(json_encode($postData))
        ]);

        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if (curl_errno($ch)) {
            $error = curl_error($ch);
            curl_close($ch);
            $this->error('网络请求失败: ' . $error);
        }

        curl_close($ch);

        // 解析响应
        $response = json_decode($result, true);
        Log::info('接口响应: ' . $result . '，手机号: ' . $mobile);
        // var_dump($response);
        if ($response && isset($response['code']) && $response['code'] == 200) {
            // 发送成功
            Cache::set('app_login_' . $mobile, $mobile_code, 300);
            Cache::set('sms_limit_' . $mobile, time(), 60);

            $this->success('发送成功');
        } else {
            // 发送失败
            $errorMsg = '发送失败';
            if ($response && isset($response['msg'])) {
                $errorMsg .= '：' . $response['msg'];
            } elseif ($response && isset($response['code'])) {
                $errorMsg .= '，错误代码：' . $response['code'];
            } else {
                $errorMsg .= '，请检查配置';
            }
            $this->error($errorMsg);
        }
    }
    // 验证短信验证码
    public function checkSmsCode($mobile = '', $code = '')
    {
        $cacheCode = Cache::get('app_login_' . $mobile);
        if ($cacheCode && $cacheCode == $code) {
            return ['code' => 1, 'msg' => '验证码正确'];
        } else {
            return ['code' => 0, 'msg' => '验证码错误'];
        }
    }
}
